import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
print(BASE_DIR)

SECRET_KEY = 'django-insecure-htkdi-derf*&4ub=8py1n=)7%173o*m@e+z3h^m3+5c1-s-=ks'

DEBUG = False

ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "corsheaders",
    'rest_framework_simplejwt',
    'apps',
    "rest_framework",
    "drf_spectacular",
    'drf_spectacular_sidecar'
]


CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_HEADERS = ['*']
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

ROOT_URLCONF = 'server.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'server.wsgi.application'

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.mysql',
#         # 'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': 'houseking',
#         'USER': 'yujian86',
#         'PASSWORD': 'YSHGqblf999',
#         'HOST': 'rm-cn-y1i3qnlio0003ooo.rwlb.rds.aliyuncs.com',
#         'PORT': '3306',
#         'OPTIONS': {
#             "init_command": "SET foreign_key_checks = 0;",
#         }
#     }
# }
pwd = os.environ.get("PASSWORD", "123456?")
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        # 'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'houseking',
        'USER': 'hope',
        'PASSWORD': pwd,
        #docker-compose配置中
        'HOST': 'jiazheng_mysql',
        'PORT': '3306',
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
        }
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]



# 时区
TIME_ZONE = 'Asia/Shanghai'
LANGUAGE_CODE = 'zh-hans'
USE_I18N = True
USE_TZ = False

STATIC_URL = 'static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = 'media/'
# 日志
# 真实项目上线后，日志文件打印级别不能过低，因为一次日志记录就是一次文件io操作
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            # 实际开发建议使用WARNING
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            # 实际开发建议使用ERROR
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            # 日志位置,日志文件名,日志保存目录必须手动创建，注：这里的文件路径要注意BASE_DIR代表的是小luffyapi
            'filename': BASE_DIR / 'server/logs/housekeeping.log',
            # 日志文件的最大值,这里我们设置300M
            'maxBytes': 300 * 1024 * 1024,
            # 日志文件的数量,设置最大日志数量为10
            'backupCount': 10,
            # 日志格式:详细格式
            'formatter': 'verbose',
            # 文件内容编码
            'encoding': 'utf-8'
        },
    },
    # 日志对象
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'propagate': True,  # 是否让日志信息继续冒泡给其他的日志处理系统
        },
    }
}

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'apps.utils.common_exception.exception_handler',
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',  # 接口文档,
    # "DEFAULT_PERMISSION_CLASSES": [
    #     "rest_framework.permissions.IsAuthenticated",
    # ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "apps.utils.common_jwt.JWTLoginAuth",
    ],
    # 'DEFAULT_THROTTLE_CLASSES': [
    #     "rest_framework.throttling.UserRateThrottle",
    #     "rest_framework.throttling.AnonRateThrottle"
    # ],
    "DEFAULT_THROTTLE_RATES": {
        "anon": "10/m",
        "user": "10/m"
    }

}

from datetime import timedelta

SIMPLE_JWT = {
     # Access Token的有效期
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 
    
     # Refresh Token的有效期
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7), 

    # 用于指定JWT在HTTP请求头中使用的身份验证方案。默认Bearer为""
    "AUTH_HEADER_TYPES": ("Token"),
    
     # 用于生成访问令牌和刷新令牌的序列化器。 改成你自己的即可
    "TOKEN_OBTAIN_SERIALIZER": "apps.utils.common_jwt.JWT",
}


SPECTACULAR_SETTINGS = {
    'TITLE': '家政系统接口文档',
    'DESCRIPTION': '更多功能持续添加中...',
    'SERVE_INCLUDE_SCHEMA': False,
    # 'VERSION': '1.0.0',
}
BACKEND_URL = 'http://192.168.71.129:8000/'
# 前台基URL
LUFFY_URL = 'http://192.168.71.129'
# 支付宝同步异步回调接口配置
# 后台异步回调接口
NOTIFY_URL = BACKEND_URL + "order_create/"
# 前台同步回调接口，没有 / 结尾
RETURN_URL = LUFFY_URL + "success/"